package com.youdoneed.community.group.service;

import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.youdoneed.base.application.AppException;
import com.youdoneed.community.common.utils.StringUUIdUtil;
import com.youdoneed.community.forum.dao.ForumnoticeMapper;
import com.youdoneed.community.forum.entity.Forumnotice;
import com.youdoneed.community.forum.service.ForumServciceStatic;
import com.youdoneed.community.group.dao.ForumgroupMapper;
import com.youdoneed.community.group.dao.ForumgroupinvitationrecordMapper;
import com.youdoneed.community.group.dao.ForumuserapplyjoingrouprecordMapper;
import com.youdoneed.community.group.dao.ForumuserinforumgroupMapper;
import com.youdoneed.community.group.entity.Forumgroup;
import com.youdoneed.community.group.entity.Forumgroupinvitationrecord;
import com.youdoneed.community.group.entity.Forumuserapplyjoingrouprecord;
import com.youdoneed.community.group.entity.Forumuserinforumgroup;
import com.youdoneed.friends.feign.FriendsClient;
import com.youdoneed.user.feign.UserFeignClient;

@Service
public class ForumgroupinvitationrecordService {
	
	private final Logger logger = LoggerFactory.getLogger(ForumgroupinvitationrecordService.class);
	
	@Autowired
	ForumgroupinvitationrecordMapper forumgroupinvitationrecordMapper;
	@Autowired
	ForumgroupMapper forumgroupMapper;
	@Autowired
	ForumuserinforumgroupMapper forumuserinforumgroupMapper;
	@Autowired
	ForumuserapplyjoingrouprecordMapper forumuserapplyjoingrouprecordMapper;
	@Autowired
	ForumnoticeMapper forumnoticeMapper;
	@Autowired
	UserFeignClient userFeignClient;
	@Autowired
	FriendsClient friendsClient;
	private String privacy="公开";
	/**
	 * 邀请加入小组
	 * @param forumgroup
	 * @param invitedUserId
	 * @param userId
	 * @return int
	 * @author lixs
	 * @date 2017.6.25
	 */
	@Transactional
	public boolean saveApplyJoinGroupRecord(String userId, String invitedUserId, String forumGroupId){
		logger.info("saveForumGroup");
		if(!StringUtils.hasText(userId)){
			throw new AppException("邀请人id不能为空");
		}
		if(!StringUtils.hasText(invitedUserId)){
			throw new AppException("被邀请人id不能为空");
		}
		if(!StringUtils.hasText(forumGroupId)){  
			throw new AppException("被邀请的小组id不能为空");
		}
		if(userId.equals(invitedUserId)){
			throw new AppException("只能邀请除自己之外的好友进组哦");
		}
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumGroupId);
		if(forumgroup==null){
			throw new AppException("未找到该小组的信息");
		}
		if(forumgroup.getMemberCount()>=2000){
			throw new AppException("小组成员不能超过2000人 ");
		}
		if(forumgroup.getGroupType().equals(ForumgroupStatic.forum_group_type_for_delete)){
			throw new AppException("该小组已经被解散");
		}
		
		Forumuserinforumgroup forumuserinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(userId, forumGroupId);
		if(forumuserinforumgroup==null){
			throw new AppException("你不是该小组的成员，无法邀请别人");
		}
		Forumuserinforumgroup userinforumgroup = forumuserinforumgroupMapper.selectByUserIdAndGroupId(invitedUserId, forumGroupId);
		if(userinforumgroup!=null){
			throw new AppException("您邀请的用户已经在小组中了哦，不能再进行邀请了");
		}
		
		if(forumgroup.getPrivacySetting()==ForumgroupStatic.privacy_public){
			privacy="公开";
		}
		if(forumgroup.getPrivacySetting()==ForumgroupStatic.privacy_close){
			privacy="封闭";
		}
		if(forumgroup.getPrivacySetting()==ForumgroupStatic.privacy_private){
			privacy="私密";
		}
		Forumgroupinvitationrecord forumgroupinvitationrecords = forumgroupinvitationrecordMapper.selectByGroupIdUserIdAndInvitedUserId(userId, invitedUserId, forumGroupId);
		if(forumgroupinvitationrecords!=null){
			throw new AppException("你已发送过邀请");
		}
		//保存邀请记录
		Forumgroupinvitationrecord forumgroupinvitationrecord = new Forumgroupinvitationrecord();
		forumgroupinvitationrecord.setCreateDate(new Date());
		forumgroupinvitationrecord.setGroupId(forumGroupId);
		forumgroupinvitationrecord.setGroupInvitationRecordId(StringUUIdUtil.getUUID());
		forumgroupinvitationrecord.setInvitedUserId(invitedUserId);
		forumgroupinvitationrecord.setInviteStatus(ForumgroupStatic.invite_status_agree);
		forumgroupinvitationrecord.setUserId(userId);
		forumgroupinvitationrecordMapper.insert(forumgroupinvitationrecord);
				
		//保存邀请通知
		Forumnotice forumnotice = new Forumnotice();
		forumnotice.setCreateDate(new Date());
		forumnotice.setForumNoticeId(StringUUIdUtil.getUUID());
		forumnotice.setNoticeType(ForumServciceStatic.gpInvitationNotice);
		forumnotice.setNoticeUserHeadUrl(userFeignClient.getUser(userId).getData().getImageUrl());
		forumnotice.setNoticeUserId(userId);
		forumnotice.setReadStatus(Forumnotice.UN_READ);
		forumnotice.setSourceId(forumGroupId);
		forumnotice.setUserId(invitedUserId);
		forumnotice.setNoticeUserNickname(userFeignClient.getUser(userId).getData().getName());
		forumnotice.setSourceDesc(forumgroup.getGroupName());
		forumnoticeMapper.insertSelective(forumnotice);
		logger.info("qqqqqqqqqqqqq"+privacy);
		
		
		//邀请用户加群时无需用户同意，也无需群主审核即可进群。
		Forumuserinforumgroup forumuserinforumgroupNew=new Forumuserinforumgroup();
		forumuserinforumgroupNew.setUserId(forumgroupinvitationrecord.getInvitedUserId());
		forumuserinforumgroupNew.setForumGroupId(forumGroupId);
		forumuserinforumgroupNew.setCreateDate(new Date());
		forumuserinforumgroupNew.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
		forumuserinforumgroupNew.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
		forumuserinforumgroupNew.setUserInForumGroupId(StringUUIdUtil.getUUID());
		forumuserinforumgroupMapper.insert(forumuserinforumgroupNew);
		
		List<Forumuserinforumgroup> forumuserinforumgroupnew = forumuserinforumgroupMapper.selectByGroupId(forumGroupId);
		
		
		//调用环信接口，添加群组成员（单个）
		friendsClient.addGroupUser(forumgroup.getHuanxinGroupId(), invitedUserId);
		
		//更新群组人数
		forumgroup.setMemberCount(forumuserinforumgroupnew.size());
		forumgroupMapper.updateByPrimaryKey(forumgroup);
		
		return true;
	}

	
	
	/**
	 * 获取被邀请记录
	 * @param userId
	 * @param currentPage
	 * @param rows
	 * @author lixs
	 * @Date 2017.7.8
	 */
	@Transactional
	public List<Forumgroupinvitationrecord> getInvitationsByUserId(String userId,Integer currentPage,Integer rows){
		/**
		 * lxs
		 */
		logger.info("getInvitations");
		if(!StringUtils.hasText(userId)){
			throw new AppException("邀请用户不能为空");
		}
		PageHelper.startPage(currentPage, rows);
		List<Forumgroupinvitationrecord> forumgroupinvitationrecord = forumgroupinvitationrecordMapper.getInvitations(userId);
		if(null==forumgroupinvitationrecord){
			throw new AppException("获取邀请列表失败");
		}
		return forumgroupinvitationrecord;
	}
	
	/**
	 * 处理邀请
	 * @param groupInvitationRecordId
	 * @param inviteStatus 0：邀请中，1：同意加入，2：拒绝加入
	 * @return int
	 * @author lxs
	 * @date 2017.6.25
	 */
	@Transactional
	public int manageInvitation(String groupInvitationRecordId, Integer inviteStatus){
		if(!StringUtils.hasText(groupInvitationRecordId)){
			throw new AppException("邀请id不能为空");
		}
		if(inviteStatus==null){
			throw new AppException("邀请状态不能为空");
		}
		Forumgroupinvitationrecord forumgroupinvitationrecord = forumgroupinvitationrecordMapper.selectByPrimaryKey(groupInvitationRecordId);
		if(forumgroupinvitationrecord==null){
			throw new AppException("邀请记录不存在");
		}
		if(forumgroupinvitationrecord.getInviteStatus()!=ForumgroupStatic.invite_status_ing){
			throw new AppException("这条邀请记录已经被用户处理过了，无法再次对它进行操作");
		  } 
		forumgroupinvitationrecord.setInviteStatus(inviteStatus);
		forumgroupinvitationrecord.setCreateDate(new Date());
		forumgroupinvitationrecordMapper.updateByPrimaryKeyForInviteStatus(groupInvitationRecordId, inviteStatus);
		
		Forumgroup forumgroup = forumgroupMapper.selectByPrimaryKey(forumgroupinvitationrecord.getGroupId());
		if(forumgroup==null){
			throw new AppException("未找到该小组记录");
		}
		//邀请别人进群时，如果被邀请人同意，并且群是公开群或者邀请进群的用户是群主，则直接加群.
		if(forumgroupinvitationrecord.getInviteStatus()==ForumgroupStatic.invite_status_agree){
		if(forumgroup.getPrivacySetting()==ForumgroupStatic.privacy_public||forumgroupinvitationrecord.getUserId().equals(forumgroup.getLeaderUserId())){
			Forumuserinforumgroup forumuserinforumgroupNew=new Forumuserinforumgroup();
			forumuserinforumgroupNew.setUserId(forumgroupinvitationrecord.getInvitedUserId());
			forumuserinforumgroupNew.setForumGroupId(forumgroupinvitationrecord.getGroupId());
			forumuserinforumgroupNew.setCreateDate(new Date());
			forumuserinforumgroupNew.setUserGroupChatSetting(ForumgroupStatic.user_in_group_chat_setting_agree);
			forumuserinforumgroupNew.setUserGroupForumMessageSetting(ForumgroupStatic.user_in_group_forum_message_setting_yes);
			forumuserinforumgroupNew.setUserInForumGroupId(StringUUIdUtil.getUUID());
			forumuserinforumgroupMapper.insert(forumuserinforumgroupNew);
			
			//小组人数加1
			forumgroup.setMemberCount(forumgroup.getMemberCount()+1);
			return forumgroupMapper.updateByPrimaryKey(forumgroup);
	}
		//如果群是隐私群，则将该条邀请记录存入申请记录中，并记为待处理
		if(forumgroup.getPrivacySetting()!=ForumgroupStatic.privacy_public){
			Forumuserapplyjoingrouprecord forumuserapplyjoingrouprecord = new Forumuserapplyjoingrouprecord();
			forumuserapplyjoingrouprecord.setForumGroupId(forumgroupinvitationrecord.getGroupId());
			forumuserapplyjoingrouprecord.setUserApplyJoinGroupRecordId(StringUUIdUtil.getUUID());
			forumuserapplyjoingrouprecord.setApplyStatus(ForumgroupStatic.apply_status_ing);
			forumuserapplyjoingrouprecord.setCreateDate(new Date());
			forumuserapplyjoingrouprecord.setUserId(forumgroupinvitationrecord.getInvitedUserId());
			return forumuserapplyjoingrouprecordMapper.insert(forumuserapplyjoingrouprecord);
		}
      }
		if(forumgroupinvitationrecord.getInviteStatus()==ForumgroupStatic.invite_status_refuse){
			logger.info("被邀请者拒绝加入");
	  } 
		if(forumgroupinvitationrecord.getInviteStatus()==ForumgroupStatic.invite_status_ing){
			logger.info("被邀请者还未处理请求");
	  }
			return 0;
	}
	
	/**
	 * 创建邀请记录并保存
	 * @param forumgroupinvitationrecord
	 * @author lixs
	 * @Date 2017.7.1
	 */
	@Transactional
	public int saveInvitationrecord(Forumgroupinvitationrecord forumgroupinvitationrecord){
		if(forumgroupinvitationrecord==null){
			throw new AppException("传入的对象不能为空");
		}
		if(!StringUtils.hasText(forumgroupinvitationrecord.getUserId())){
			throw new AppException("邀请人id不能为空");
		}
		if(!StringUtils.hasText(forumgroupinvitationrecord.getGroupId())){
			throw new AppException("小组id不能为空");
		}
		if(!StringUtils.hasText(forumgroupinvitationrecord.getInvitedUserId())){
			throw new AppException("被邀请人id不能为空");
		}
		
		
		Forumgroupinvitationrecord forumgroupinvitation = new Forumgroupinvitationrecord();
		forumgroupinvitation.setCreateDate(new Date());
		forumgroupinvitation.setGroupId(forumgroupinvitationrecord.getGroupId());
		forumgroupinvitation.setInvitedUserId(forumgroupinvitationrecord.getInvitedUserId());
		forumgroupinvitation.setUserId(forumgroupinvitationrecord.getUserId());
		forumgroupinvitation.setGroupInvitationRecordId(StringUUIdUtil.getUUID());
		forumgroupinvitation.setInviteStatus(ForumgroupStatic.invite_status_ing);
		return forumgroupinvitationrecordMapper.insert(forumgroupinvitation);
	}
}
